package com.gitee.zzh.common;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class MyIOUtils {
    /**
     * 读取文件内容
     *
     * @param filePath 文件路径
     * @return 字符串
     */
    public static String getText(String filePath) {
        try {
            return Files.readString(Path.of(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件写入文本内容
     *
     * @param path 文件路径
     * @param context 文本内容
     */
    public static void append(String path, String context) {
        try {
            Files.writeString(Paths.get(path), context, StandardOpenOption.APPEND);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建文件或者清空文件内容
     *
     * @param filePath 文件路劲
     */
    public static void createOrClear(String filePath) {
        File file = new File(filePath);
        if(!file.exists()) {
            try {
                System.out.println("创建文件是否成功：" + file.createNewFile());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        try (FileWriter fileWriter = new FileWriter(file)) {
            fileWriter.write("");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
